<template>
  <div id="sysParamIdv">
    <Breadcrumb content="系统参数设置" />
    <div class="bodyContent">
      <el-tabs type="border-card">
        <el-tab-pane label="系统参数">
          <Splitpanes>
            <Pane size="20">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="smallToolTitle">系统参数</div>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="findSysParamList"></vxe-button>
                </template>
              </vxe-toolbar>

              <el-scrollbar style="height: calc(100% - 40px)">
                <div class="sampleType">
                  <el-scrollbar>
                    <el-tree :expand-on-click-node="false" :default-expand-all="true" :data="sysParamList" node-key="id" ref="dataTreeRef" highlight-current class="tools-tree" @node-click="handleClickType" v-loading="tloading">
                      <template #default="{ data, node }">
                        <span>{{ data.name }}</span>
                        <div>
                          <span>
                            <!-- 新增  -->
                            <el-button type="success" class="cirBtn" size="small" icon="Plus" circle v-if="data.isModule" @click="addSysParamDialog(data)"></el-button>
                            <!-- 编辑  -->
                            <el-button type="warning" class="cirBtn" size="small" icon="Edit" circle v-if="!data.isModule" @click="editSysParamDialog(data, node)"></el-button>
                            <!-- 删除  -->
                            <el-button type="info" class="cirBtn" size="small" icon="Delete" circle v-if="!data.isModule" @click="deleteSysParam(data)"></el-button>
                          </span>
                        </div>
                      </template>
                    </el-tree>
                  </el-scrollbar>
                </div>
              </el-scrollbar>

              <!-- 中间字段弹框 -->
              <el-dialog :title="titleType()" :show-close="false" v-model="showDialog" append-to-body width="500px" :close-on-click-modal="false">
                <el-form ref="sysParamFormRef" :model="sysParamForm" :rules="sysParamFormRule" label-width="100px" class="form-input-m" inline-message>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item prop="code" label="编号">
                        <el-input type="text" v-model="sysParamForm.code" placeholder="请输入字段编号" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item prop="name" label="名称">
                        <el-input type="text" v-model="sysParamForm.name" placeholder="请输入字段名称" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item prop="classify" label="组件类型">
                        <el-radio-group v-model="sysParamForm.classify">
                          <el-radio-button label="1" @click.prevent="changeCorrection('1')">仪器</el-radio-button>
                          <el-radio-button label="2" @click.prevent="changeCorrection('2')">报告单元</el-radio-button>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="2"> </el-col>
                    <el-col :span="6">
                      <el-checkbox v-model="sysParamForm.isLocal" @change="changeIsLocal">本地参数</el-checkbox>
                    </el-col>
                    <el-col :span="6">
                      <el-checkbox v-model="sysParamForm.isComputer" :disabled="!sysParamForm.isLocal">是否显示电脑列表</el-checkbox>
                    </el-col>
                    <el-col :span="10"> </el-col>

                    <el-col :span="24">
                      <el-form-item label="是否删改" prop="isEdit">
                        <el-switch v-model="sysParamForm.isEdit" inline-prompt active-text="是" inactive-text="否"></el-switch>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item prop="order" label="排序">
                        <el-input-number v-model="sysParamForm.seq" :min="1" :max="1000" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>

                <div class="dialog-footer flex right justify-end">
                  <el-button type="primary" @click="saveSysParam('sysParamFormRef')">保存</el-button>
                  <el-button @click="closeDialog('sysParamFormRef')">取消</el-button>
                </div>
              </el-dialog>
            </Pane>

            <Pane size="80">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="smallToolTitle">参数分组</div>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="gloading" :disabled="disabledTag" @click="findGroupList"></vxe-button>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建分组" :disabled="disabledTag" @click="addGroupDialog()"></vxe-button>
                </template>
              </vxe-toolbar>

              <el-tabs v-if="groupList && groupList.length > 0" v-model="activeName" type="card" class="demo-tabs" closable @tab-remove="tabRemoveClick" @tab-click="tabHandleClick">
                <el-tab-pane v-bind:key="idx" v-for="(group, idx) in groupList" :label="`${group.code} ${group.title}`" :name="idx">
                  <Splitpanes style="height: 100%">
                    <Pane size="10">
                      <div class="padding-lr-xs">
                        <vxe-button type="text" content="输入框" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('input')"></vxe-button>
                        <vxe-button type="text" content="数值框" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('integer')"></vxe-button>
                        <vxe-button type="text" content="日期选择" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('date')"></vxe-button>
                        <vxe-button type="text" content="复选框" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('checkbox')"></vxe-button>
                        <vxe-button type="text" content="复选框组" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('checkboxgroup')"></vxe-button>
                        <vxe-button type="text" content="单选按钮组" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('radiogroup')"></vxe-button>
                        <vxe-button type="text" content="开关按钮" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('switch')"></vxe-button>
                        <vxe-button type="text" content="下拉选择" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('select')"></vxe-button>
                        <vxe-button type="text" content="文本域" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('textarea')"></vxe-button>
                        <vxe-button type="text" content="颜色框" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('color')"></vxe-button>
                        <vxe-button type="text" content="下拉业务表" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('sltBusTable')"></vxe-button>
                        <vxe-button type="text" content="多选业务表" class="button-blue margin-tb-xs" style="width: 100%" @click="addFormItem('checkBusTable')"></vxe-button>
                      </div>
                    </Pane>
                    <Pane size="55">
                      <div class="saveBtn">
                        <vxe-button type="text" content="保存" class="button-blue margin-left-xs" @click="saveParamFieldList"></vxe-button>
                      </div>
                      <vxe-toolbar perfect>
                        <template #buttons>
                          <div class="toolbartitle">详情</div>
                        </template>
                      </vxe-toolbar>

                      <div class="padding-lr-xs formBox">
                        <el-scrollbar height="100%">
                          <vxe-form :data="formData">
                            <vxe-form-item class="padding-lr-xs" :class-name="formItm.isCurrent ? 'dashed lines-orange bg-blue light' : ''" :align="formItm.align" :title="formItm.title" :field="formItm.field" :title-width="formItm.titleWidth" :title-colon="formItm.titleColon === 1" :title-asterisk="formItm.titleAsterisk === 1" :title-overflow="formItm.titleOverflow === 1" :show-title="formItm.showTitle === 1" :title-align="formItm.titleAlign" :vertical="formItm.vertical === 1" :content-class-name="formItm.contentClassName" :visible="formItm.visible === 1" :span="formItm.span" v-for="(formItm, formIdx) in paramFieldList" :key="formIdx">
                              <template #title>
                                <div @click="formItemCLick(formItm, formIdx)">
                                  <span class="padding-left-xs">{{ `${formItm.code} ${formItm.title}` }}</span>
                                </div>
                              </template>
                              <template #default="params">
                                <div class="flex justify-start" @click="formItemCLick(formItm, formIdx)">
                                  <vxe-input v-if="formItm.compType === 'input'" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                                  <vxe-input v-if="formItm.compType === 'date' || formItm.compType === 'datetime'" :type="formItm.compType === 'date' ? 'date' : 'datetime'" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                                  <vxe-checkbox-group v-if="formItm.compType === 'checkboxgroup'" @click="changeEvent(params)">
                                    <vxe-checkbox :label="itm.label" :content="itm.content" v-for="(itm, idx) in formItm.fieldOptions" :key="idx"></vxe-checkbox>
                                  </vxe-checkbox-group>
                                  <vxe-radio-group v-if="formItm.compType === 'radiogroup'">
                                    <vxe-radio :label="itm.label" :content="itm.content" v-for="(itm, idx) in formItm.fieldOptions" :key="idx"></vxe-radio>
                                  </vxe-radio-group>
                                  <vxe-checkbox v-if="formItm.compType === 'checkbox'"></vxe-checkbox>
                                  <vxe-input v-if="formItm.compType === 'integer'" type="integer" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                                  <vxe-switch v-if="formItm.compType === 'switch'" open-value="1" close-value="0"></vxe-switch>
                                  <vxe-select v-if="formItm.compType === 'select'" placeholder="请选择">
                                    <vxe-option v-for="(itm, idx) in formItm.fieldOptions" :key="idx" :value="itm.label" :label="itm.content"></vxe-option>
                                  </vxe-select>
                                  <vxe-textarea v-if="formItm.compType === 'textarea'" placeholder="请输入"></vxe-textarea>
                                  <vxe-select v-if="formItm.compType === 'sltBusTable'" placeholder="可清除" transfer clearable @focus="getTableDataList(formItm)">
                                    <vxe-option v-for="(tableData, index) in tableDataList" :key="index" :value="tableData[formItm.correValue]" :label="tableData[formItm.correLabel]"></vxe-option>
                                  </vxe-select>
                                  <vxe-select v-if="formItm.compType === 'checkBusTable'" placeholder="可清除" transfer multiple clearable @focus="getTableDataList(formItm)">
                                    <vxe-option v-for="(tableData, index) in tableDataList" :key="index" :value="tableData[formItm.correValue]" :label="tableData[formItm.correLabel]"></vxe-option>
                                  </vxe-select>

                                  <el-color-picker v-if="formItm.compType === 'color'" />

                                  <vxe-button type="text" class="button-red right-Btn" icon="vxe-icon-delete" v-if="sltSysParam.isEdit" @click="deleteParamField(formItm)"></vxe-button>
                                </div>
                              </template>
                            </vxe-form-item>
                          </vxe-form>
                        </el-scrollbar>
                      </div>
                    </Pane>
                    <Pane size="35">
                      <el-tabs type="border-card">
                        <el-tab-pane label="基本属性">
                          <div class="padding-lr-xs">
                            <vxe-form title-width="90" v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex]" ref="formRef" :data="paramFieldList[sltGroup.editFormItemIndex]" title-align="right">
                              <vxe-form-item title="编号" field="code" span="24">
                                <template #default="params">
                                  <vxe-input v-model="params.data.code" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                                </template>
                              </vxe-form-item>
                              <vxe-form-item title="属性名" field="field" span="24">
                                <template #default="params">
                                  <vxe-input v-model="params.data.field" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                                </template>
                              </vxe-form-item>
                              <vxe-form-item title="标题" field="title" span="24">
                                <template #default="params">
                                  <vxe-input v-model="params.data.title" placeholder="请输入" clearable @change="changeEvent(params)"></vxe-input>
                                </template>
                              </vxe-form-item>
                              <vxe-form-item title="对齐方式" field="titleAlign" span="24">
                                <template #default="params">
                                  <vxe-select v-model="params.data.titleAlign" placeholder="请选择对齐方式" @change="changeEvent(params)">
                                    <vxe-option value="right" label="右对齐"></vxe-option>
                                    <vxe-option value="left" label="左对齐"></vxe-option>
                                  </vxe-select>
                                </template>
                              </vxe-form-item>
                              <vxe-form-item title="占比" field="span" span="24">
                                <template #default="params">
                                  <vxe-input type="integer" v-model="params.data.span" placeholder="请输入0-24" clearable @change="changeEvent(params)" min="1" max="24"></vxe-input>
                                </template>
                              </vxe-form-item>
                              <vxe-form-item title="标题宽度" field="titleWidth" span="24">
                                <template #default="params">
                                  <vxe-input type="integer" v-model="params.data.titleWidth" placeholder="请输入0-200" clearable @change="changeEvent(params)" min="1" max="200">
                                    <template #suffix>
                                      <span>px</span>
                                    </template>
                                  </vxe-input>
                                </template>
                              </vxe-form-item>
                              <vxe-form-item title="备注" field="remark" span="24">
                                <template #default="params">
                                  <vxe-textarea v-model="params.data.remark" placeholder="请输入" clearable></vxe-textarea>
                                </template>
                              </vxe-form-item>
                              <vxe-form-item title="顺序号" field="seq" span="24">
                                <template #default="params">
                                  <vxe-input type="number" v-model="params.data.seq" placeholder="请输入" clearable @blur="sortAgain"></vxe-input>
                                </template>
                              </vxe-form-item>
                              <vxe-form-item v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'select' || paramFieldList[sltGroup.editFormItemIndex].compType === 'radiogroup' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkboxgroup')" title="数据来源" field="fieldSource" span="24" :item-render="{}" title-overflow>
                                <template #default="params">
                                  <vxe-select v-model="params.data.fieldSource" placeholder="请选择数据来源" clearable @change="changeEvent(params)">
                                    <vxe-option value="1" label="字典"></vxe-option>
                                    <vxe-option value="2" label="业务表"></vxe-option>
                                    <vxe-option value="3" label="固定数组"></vxe-option>
                                  </vxe-select>
                                </template>
                              </vxe-form-item>

                              <vxe-form-item v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'sltBusTable' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkBusTable')" title="选择表" field="correTable" span="24" :item-render="{}" title-overflow>
                                <template #default="params">
                                  <SelectDataList ref="employeeSelectRef" :url="'/api/sys/basDictTable/findAllTableList'" :displayField="[
                                      { title: '编号', props: 'TABLE_NAME' }, //列标题
                                      { title: '名称', props: 'COMMENTS' }
                                    ]" :searchParam="{
                                      //seachValue: form.hisEmployeeCode
                                    }" :inputKeyName="'seachValue'" :isPage="false" :title="'点击选择表'" @selectDataRow="SelectRowClick" @clearValue="clearValueHandler" @sliceValue="sliceHandler" v-model="params.data.correTable" />
                                </template>
                              </vxe-form-item>

                              <vxe-form-item v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'sltBusTable' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkBusTable')" title="选择Label" field="correLabel" span="24" :item-render="{}" title-overflow>
                                <template #default="params">
                                  <vxe-select v-model="params.data.correLabel" placeholder="请选择表字段" clearable>
                                    <vxe-option v-for="correColumn in correColumnList" :key="correColumn.columnId" :label="correColumn.comments" :value="correColumn.columnName"></vxe-option>
                                  </vxe-select>
                                </template>
                              </vxe-form-item>
                              <vxe-form-item v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'sltBusTable' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkBusTable')" title="选择Value" field="correValue" span="24" :item-render="{}" title-overflow>
                                <template #default="params">
                                  <vxe-select v-model="params.data.correValue" placeholder="请选择表字段" clearable>
                                    <vxe-option v-for="correColumn in correColumnList" :key="correColumn.columnId" :label="correColumn.comments" :value="correColumn.columnName"></vxe-option>
                                  </vxe-select>
                                </template>
                              </vxe-form-item>
                            </vxe-form>
                            <vxe-toolbar v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'select' || paramFieldList[sltGroup.editFormItemIndex].compType === 'radiogroup' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkboxgroup')" perfect class-name="bg-gray">
                              <template #buttons>
                                <span class="text-bold">可取值</span>
                              </template>
                              <template #tools>
                                <vxe-button type="text" class="button-red deleteValueBtn" content="删除" @click="removeSelectRowEvent"></vxe-button>
                                <vxe-button type="text" class="button-blue" content="添加" @click="insertEvent"></vxe-button>
                              </template>
                            </vxe-toolbar>
                            <div v-if="sltGroup && paramFieldList[sltGroup.editFormItemIndex] && paramFieldList[sltGroup.editFormItemIndex].compType && (paramFieldList[sltGroup.editFormItemIndex].compType === 'select' || paramFieldList[sltGroup.editFormItemIndex].compType === 'radiogroup' || paramFieldList[sltGroup.editFormItemIndex].compType === 'checkboxgroup')">
                              <vxe-table border align="center" show-overflow keep-source height="auto" :row-config="{ isCurrent: true }" :data="paramFieldList[sltGroup.editFormItemIndex].fieldOptions" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: false }" ref="xTableOptions">
                                <vxe-column type="seq" title="#" width="30"></vxe-column>
                                <vxe-column field="label" title="选项值" :edit-render="{ autofocus: '.vxe-input--inner' }">
                                  <template #edit="{ row }">
                                    <vxe-input v-model="row.label" type="text"></vxe-input>
                                  </template>
                                </vxe-column>
                                <vxe-column field="content" title="选项描述" :edit-render="{ autofocus: '.vxe-input--inner' }">
                                  <template #edit="{ row }">
                                    <vxe-input v-model="row.content" type="text"></vxe-input>
                                  </template>
                                </vxe-column>
                              </vxe-table>
                            </div>
                          </div>
                        </el-tab-pane>
                        <el-tab-pane label="页签属性">
                          <div class="padding-lr-xs">
                            <el-form :ref="'groupEditFormRef' + idx" :model="editGroupForm" :rules="groupFormRule" label-width="100px" class="form-input-m" inline-message>
                              <el-row>
                                <el-col :span="24">
                                  <el-form-item prop="code" label="编号">
                                    <el-input type="text" v-model="editGroupForm.code" placeholder="请输入分组编号" clearable></el-input>
                                  </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                  <el-form-item prop="title" label="名称">
                                    <el-input type="text" v-model="editGroupForm.title" placeholder="请输入分组名称" clearable></el-input>
                                  </el-form-item>
                                </el-col>
                                <el-col :span="24">
                                  <el-form-item prop="order" label="排序">
                                    <el-input-number v-model="editGroupForm.seq" :min="1" :max="1000" />
                                  </el-form-item>
                                </el-col>
                              </el-row>
                            </el-form>

                            <div class="dialog-footer flex right justify-end">
                              <vxe-button type="text" content="保存" class="button-blue margin-left-xs" @click="editGroup('groupEditFormRef' + idx)"></vxe-button>
                            </div>
                          </div>
                        </el-tab-pane>
                      </el-tabs>
                    </Pane>
                  </Splitpanes>
                </el-tab-pane>
              </el-tabs>
              <div v-if="!groupList || groupList.length <= 0">
                <noData :msg="'暂无配置项'"></noData>
              </div>
              <el-dialog title="新建分组" :show-close="false" v-model="showGroupDialog" append-to-body width="500px" :close-on-click-modal="false">
                <el-form ref="groupFormRef" :model="addGroupForm" :rules="groupFormRule" label-width="100px" class="form-input-m" inline-message>
                  <el-row>
                    <el-col :span="24">
                      <el-form-item prop="code" label="编号">
                        <el-input type="text" v-model="addGroupForm.code" placeholder="请输入分组编号" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item prop="title" label="名称">
                        <el-input type="text" v-model="addGroupForm.title" placeholder="请输入分组名称" clearable></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item prop="order" label="排序">
                        <el-input-number v-model="addGroupForm.seq" :min="1" :max="1000" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>

                <div class="dialog-footer flex right justify-end">
                  <el-button type="primary" @click="addGroup('groupFormRef')">保存</el-button>
                  <el-button @click="closeGroupDialog('groupFormRef')">取消</el-button>
                </div>
              </el-dialog>
            </Pane>
          </Splitpanes>
        </el-tab-pane>
        <el-tab-pane label="操作日志">
          <LogInfo requestUrl="/api/sys/sysParam"></LogInfo>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区==========
import { ref, reactive, getCurrentInstance, nextTick, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue'; //面包屑
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { AppStore } from '../../stores/store';
import noData from '@/components/NoData.vue';
import { isEmpty } from 'lodash';
import type { VxeTableInstance } from 'vxe-table';
import SelectDataList from '@/components/SelectDataList.vue';
import LogInfo from '@/components/LogInfo.vue'; //操作日志

// 全局变量定义区 ==========
let store = AppStore();

let showDialog = ref(false); //中间字段弹框
let showGroupDialog = ref(false);
let tloading = ref(false); //加载状态
let gloading = ref(false); //加载状态
let sysParamList: any = reactive([]);
let groupList: any = reactive([]);
let paramFieldList: any = reactive([]);
let sltSysParam: any = reactive({});
let correColumnList: any = reactive([]);
let tableDataList: any = reactive([]); //选择动态表集合

let disabledTag = ref(true);
let formData: any = {};
let sltGroup: any = {};
let activeName = ref(0);
let searchForm = {
  searchValue: ''
};
let searchGroupForm = { searchValue: '' };

let sysParamForm = reactive({
  id: null,
  code: '',
  name: '',
  seq: 0,
  orgId: '',
  remark: '',
  moduleId: '',
  classify: '',
  isEdit: true,
  isLocal: false,
  isComputer: false
});
let sysParamFormRule = {
  name: [
    {
      required: true,
      message: '请输入字段名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

let addGroupForm = reactive({
  id: null,
  pid: null,
  grade: 0,
  code: '',
  title: '',
  seq: 0,
  orgId: '',
  remark: ''
});
let editGroupForm = reactive({
  id: null,
  pid: null,
  grade: 0,
  code: '',
  title: '',
  seq: 0,
  orgId: '',
  remark: ''
});
let groupFormRule = {
  title: [
    {
      required: true,
      message: '请输入字段名称',
      trigger: 'blur'
    },
    {
      min: 2,
      max: 20,
      message: '长度为2到20个字符',
      trigger: 'blur'
    }
  ]
};

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findSysParamList();
});

function findSysParamList() {
  tloading.value = true;
  sysParamList.length = 0; //放入数据前清空数据
  const url = '/api/sys/sysParam/findSysParamList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: searchForm.searchValue }
    })
    .then((res: any) => {
      sysParamList.push(...res.data);
      if (sysParamList.length > 0) {
        if (isEmpty(sltSysParam)) {
          const sltObj = getChildren(sysParamList[0]);
          setCurTypeNode(sltObj.id);
          const isModule = sltObj.isModule;
          sltSysParam = reactive({});
          if (!isModule) {
            sltSysParam = sltObj;
            findGroupList();
          } else {
            paramFieldList.length = 0;
            groupList.length = 0;
          }
        } else {
          setCurTypeNode(sltSysParam.id);
        }

        //如果点击的当前行数据是父级，那就禁用质控品维护的按钮
        if (!sltSysParam.id) {
          disabledTag.value = true;
        } else {
          //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
          disabledTag.value = false;
        }
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的字段列表失败',VxeNotifyType.error)
    });
}

//点击左侧树
function handleClickType(obj: any, node: any, data: any) {
  activeName.value = 0;
  const isModule = obj.isModule;
  sltSysParam = reactive({});
  if (!isModule) {
    sltSysParam = obj;
    findGroupList();
  } else {
    paramFieldList.length = 0;
    groupList.length = 0;
  }
  //如果点击的当前行数据是父级，那就禁用质控品维护的按钮
  if (!sltSysParam.id) {
    disabledTag.value = true;
  } else {
    //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
    disabledTag.value = false;
  }
}

function groupRowClick({ row }: any) {
  sltGroup = row;
  editGroupForm.id = row.id;
  editGroupForm.pid = row.pid;
  editGroupForm.orgId = row.orgId;
  editGroupForm.code = row.code;
  editGroupForm.title = row.title;
  editGroupForm.grade = row.grade;
  editGroupForm.seq = row.seq;
  editGroupForm.remark = row.remark;
  findParamFieldList();
}

// 新建一级字典字段
function addSysParamDialog(row: any) {
  sysParamForm.seq = sysParamList.length + 1;
  sysParamForm.moduleId = row.id;
  showDialog.value = true;
}
// 新建一级字典字段
function addGroupDialog() {
  addGroupForm.pid = sltSysParam.id;
  addGroupForm.seq = groupList.length + 1;
  showGroupDialog.value = true;
}
// 判断中间弹框显示的标题
function titleType() {
  if (sysParamForm.id) {
    return `编辑参数`;
  } else if (!sysParamForm.id) {
    return `新建参数`;
  }
}

// 中间字段弹框取消按钮
function closeDialog(formMiddleName: any) {
  const el: any = proxy.$refs[formMiddleName];
  // 移除校验结果
  el.clearValidate();
  clearForm();
  showDialog.value = false;
}

function closeGroupDialog(formMiddleName: any) {
  const el: any = proxy.$refs[formMiddleName];
  // 移除校验结果
  el.clearValidate();
  clearGroupForm();
  showGroupDialog.value = false;
}
// 清空中间字段弹框表单
function clearForm() {
  sysParamForm.id = null;
  sysParamForm.orgId = '';
  sysParamForm.code = '';
  sysParamForm.name = '';
  sysParamForm.seq = 0;
  sysParamForm.remark = '';
  sysParamForm.moduleId = '';
  sysParamForm.classify = '';
  sysParamForm.isEdit = true;
  sysParamForm.isLocal = false;
  sysParamForm.isComputer = false;
}

function clearGroupForm() {
  addGroupForm.id = null;
  addGroupForm.pid = '';
  addGroupForm.orgId = '';
  addGroupForm.code = '';
  addGroupForm.title = '';
  addGroupForm.grade = 0;
  addGroupForm.seq = 0;
  addGroupForm.remark = '';
}
function saveSysParam(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    if (sysParamForm.id === null) {
      const url = '/api/sys/sysParam/addSysParam';
      const user = {
        code: sysParamForm.code,
        name: sysParamForm.name,
        seq: sysParamForm.seq,
        remark: sysParamForm.remark,
        orgId: store.userInfo.orgId,
        moduleId: sysParamForm.moduleId,
        classify: sysParamForm.classify,
        isEdit: sysParamForm.isEdit,
        isLocal: sysParamForm.isLocal,
        isComputer: sysParamForm.isComputer
      };
      proxy.$http
        .post(url, user)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            clearForm();
            showDialog.value = false;
            findSysParamList();
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          VxeMessage('新增失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/api/sys/sysParam/editSysParam';
      const user = {
        id: sysParamForm.id,
        code: sysParamForm.code,
        name: sysParamForm.name,
        seq: sysParamForm.seq,
        remark: sysParamForm.remark,
        orgId: sysParamForm.orgId,
        moduleId: sysParamForm.moduleId,
        classify: sysParamForm.classify,
        isEdit: sysParamForm.isEdit,
        isLocal: sysParamForm.isLocal,
        isComputer: sysParamForm.isComputer
      };
      proxy.$http
        .post(url, user)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            clearForm();
            showDialog.value = false;
            findSysParamList();
          } else {
            VxeMessage(res.status.msg, VxeNotifyType.error);
          }
          //VxeMessage('修改成功', VxeNotifyType.success);
          // setTimeout(() => {
          //   clearForm();
          //   showDialog.value = false;
          //   findSysParamList();
          // }, 500);
        })
        .catch((err: any) => {
          VxeMessage('修改失败', VxeNotifyType.error);
        });
    }
  });
}

function editSysParamDialog(row: any) {
  sysParamForm.id = row.id;
  sysParamForm.orgId = row.orgId;
  sysParamForm.code = row.code;
  sysParamForm.name = row.name;
  sysParamForm.seq = row.seq;
  sysParamForm.remark = row.remark;
  sysParamForm.moduleId = row.moduleId;
  sysParamForm.classify = row.classify;
  sysParamForm.isEdit = row.isEdit;
  sysParamForm.isLocal = row.isLocal;
  sysParamForm.isComputer = row.isComputer;
  showDialog.value = true;
}

function deleteSysParam(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/sys/sysParam/deleteSysParam';
      proxy.$http.post(url, row).then((res: any) => {
        if (res.status.code === 1) {
          sltSysParam = reactive({});
          findSysParamList();
          VxeMessage(res.status.msg, VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function findGroupList() {
  gloading.value = true;
  groupList.length = 0; //放入数据前清空数据
  const url = '/api/sys/sysParamField/findSysParamGroupList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: searchGroupForm.searchValue, pid: sltSysParam.id, grade: 0 }
    })
    .then((res: any) => {
      groupList.push(...res.data);
      groupRowClick({ row: groupList[activeName.value] }); //默认选中第一条数据
      gloading.value = false;
    })
    .catch((err: any) => {
      gloading.value = false;
      // VxeMessage('获取获取当前字典的字段列表失败',VxeNotifyType.error)
    });
}

function addGroup(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const url = '/api/sys/sysParamField/addSysParamField';
    const user = {
      code: addGroupForm.code,
      title: addGroupForm.title,
      pid: sltSysParam.id,
      grade: 0,
      seq: addGroupForm.seq,
      remark: addGroupForm.remark,
      orgId: store.userInfo.orgId
    };
    proxy.$http
      .post(url, user)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage(res.status.msg, VxeNotifyType.success);
          clearGroupForm();
          showGroupDialog.value = false;
          findGroupList();
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('新增失败', VxeNotifyType.error);
      });
  });
}

function editGroup(formName: any) {
  let $el = proxy.$refs[formName][0];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }

    // 修改用户
    const url = '/api/sys/sysParamField/editSysParamField';
    const user = {
      id: editGroupForm.id,
      code: editGroupForm.code,
      title: editGroupForm.title,
      pid: editGroupForm.pid,
      grade: 0,
      seq: editGroupForm.seq,
      remark: editGroupForm.remark,
      orgId: editGroupForm.orgId
    };
    proxy.$http
      .post(url, user)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage(res.status.msg, VxeNotifyType.success);
          findGroupList();
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      })
      .catch((err: any) => {
        VxeMessage('修改失败', VxeNotifyType.error);
      });
  });
}

function tabRemoveClick(targetName) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/sys/sysParamField/deleteSysParamField';
      proxy.$http.post(url, groupList[targetName]).then((res: any) => {
        if (res.status.code === 1) {
          findGroupList();
          VxeMessage(res.status.msg, VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}
function tabHandleClick(tab) {
  groupRowClick({ row: groupList[tab.index] });
}

function findParamFieldList() {
  paramFieldList.length = 0;
  const url = '/api/sys/sysParamField/findSysParamFieldList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { pid: sltGroup.id, grade: 1 }
    })
    .then((res: any) => {
      paramFieldList.push(...res.data);
      if (paramFieldList[sltGroup.editFormItemIndex].compType == 'sltBusTable' || paramFieldList[sltGroup.editFormItemIndex].compType == 'checkBusTable') {
        getTableColumns();
      }
    })
    .catch((err: any) => {
      gloading.value = false;
      // VxeMessage('获取获取当前字典的字段列表失败',VxeNotifyType.error)
    });
}
function addFormItem(compType) {
  try {
    const l = paramFieldList.length;
    const d = {
      pid: sltGroup.id,
      grade: 1,
      compType: '' /*控件类型*/,
      field: `field${l + 1}` /*字段名*/,
      title: `字段${l + 1}` /*标题*/,
      code: `${l + 1 <= 9 ? '0' + (l + 1) : l + 1}` /*属性编号*/,
      seq: l + 1 /*属性排序码*/,
      span: 24 /*栅格占据的列数（共 24 分栏）*/,
      align: 'left' /*内容对齐方式*/,
      titleAlign: 'right' /*标题对齐方式*/,
      titleWidth: '200px' /*宽度*/,
      titleColon: 0 /*是否显示标题冒号*/,
      titleAsterisk: 0 /*是否显示必填字段的红色星号*/,
      titleOverflow: 1 /*标题内容过长时显示为省略号*/,
      showTitle: 1 /*是否显示标题*/,
      vertical: 0 /*使用垂直布局*/,
      className: '' /*给表单项附加 className*/,
      contentClassName: '' /*给表单项内容附加 className*/,
      visible: 1 /*默认是否显示*/,
      visibleMethod: '' /*该方法的返回值用来决定该项是否显示*/,
      folding: '' /*默认收起*/,
      collapseNode: '' /*折叠节点*/,
      isCurrent: sltGroup.editFormItemIndex === l ? true : false /*当前编辑*/,
      fieldSource: '' /*属性数据来源*/,
      fieldOptions: [] /*属性取值集合*/,
      fieldDefValue: '' /*属性默认取值*/
    } as any;
    switch (compType) {
      case 'input':
        d.compType = 'input';
        break;
      case 'integer':
        d.compType = 'integer';
        break;
      case 'date':
        d.compType = 'date';
        break;
      case 'checkbox':
        d.compType = 'checkbox';
        break;
      case 'checkboxgroup':
        d.compType = 'checkboxgroup';
        d.fieldSource = '3';
        break;
      case 'radiogroup':
        d.compType = 'radiogroup';
        d.fieldSource = '3';
        break;
      case 'switch':
        d.compType = 'switch';
        break;
      case 'select':
        d.compType = 'select';
        d.fieldSource = '3';
        break;
      case 'textarea':
        d.compType = 'textarea';
        break;
      case 'color':
        d.compType = 'color';
        break;
      case 'sltBusTable':
        d.compType = 'sltBusTable';
        break;
      case 'checkBusTable':
        d.compType = 'checkBusTable';
        break;
      default:
        break;
    }
    paramFieldList.push(d);
    formItemCLick(d, l);
  } catch (error) {
    console.log(error);
  }
}

function formItemCLick(item, index) {
  console.log(item, index);

  sltGroup.editFormItemIndex = index;
  if (paramFieldList[sltGroup.editFormItemIndex].compType == 'sltBusTable' || paramFieldList[sltGroup.editFormItemIndex].compType == 'checkBusTable') {
    getTableColumns();
  }

  paramFieldList.forEach((m, i) => {
    if (i === index) {
      m.isCurrent = true;
    } else {
      m.isCurrent = false;
    }
  });
}

function getChildren(obj: any) {
  const children = obj.children;

  if (!isEmpty(children)) {
    return getChildren(children[0]);
  } else {
    return obj;
  }
}
// 光标定位在指定字典分类上
function setCurTypeNode(nodeId: any) {
  proxy.$nextTick(() => {
    const treeName = 'dataTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}

interface RowVO {
  label: string;
  content: string;
}

async function insertEvent(row?: RowVO | number) {
  if (paramFieldList[sltGroup.editFormItemIndex].fieldOptions) {
    const record = {
      label: '',
      content: ''
    } as RowVO;
    paramFieldList[sltGroup.editFormItemIndex].fieldOptions.push(record);
  } else {
    paramFieldList[sltGroup.editFormItemIndex].fieldOptions = [];
    const record = {
      label: '',
      content: ''
    } as RowVO;
    paramFieldList[sltGroup.editFormItemIndex].fieldOptions.push(record);
  }
}
const xTableOptions = ref<VxeTableInstance<RowVO>>();

function removeSelectRowEvent() {
  const $table = xTableOptions.value;

  if ($table) {
    const index = paramFieldList[sltGroup.editFormItemIndex].fieldOptions.findIndex((item) => item == $table[0].getCurrentRecord());
    if (index > -1) {
      paramFieldList[sltGroup.editFormItemIndex].fieldOptions.splice(index, 1);
    }
  }
}
function deleteParamField(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const index = paramFieldList.findIndex((item) => item == row);
      paramFieldList.splice(index, 1);
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function saveParamFieldList() {
  //if (paramFieldList.length > 0) {
  const url = '/api/sys/sysParamField/saveSysParamFieldList';
  const obj: any = { id: sltGroup.id };
  obj.paramFieldList = paramFieldList;
  proxy.$http
    .post(url, obj)
    .then((res: any) => {
      VxeMessage('更新成功', VxeNotifyType.success);
      setTimeout(() => {
        //findCommonRemarkList();
      }, 500);
    })
    .catch((err: any) => {
      VxeMessage('更新失败', VxeNotifyType.success);
    });
  // } else {
  //   VxeMessage('无添加或修改数据', VxeNotifyType.error);
  // }
}
//重新排序
function sortAgain() {
  paramFieldList.sort((a, b) => Number(a.seq) - Number(b.seq));
  sltGroup.editFormItemIndex = paramFieldList.findIndex((f) => f.isCurrent);
}
function changeEvent(params) {
  //todo
}

// 改变设计模式的组件类型 3选1
function changeCorrection(item: any) {
  if (item == sysParamForm.classify) {
    sysParamForm.classify = '';
  } else {
    sysParamForm.classify = item;
  }
}
function changeIsLocal() {
  if (!sysParamForm.isLocal) {
    sysParamForm.isComputer = false;
  }
}

// 点击组件表格行
function SelectRowClick(row) {
  paramFieldList[sltGroup.editFormItemIndex].correTable = row.TABLE_NAME;
  getTableColumns();
}
// 清空组件输入框
function clearValueHandler() {
  paramFieldList[sltGroup.editFormItemIndex].correTable = '';
}
// 键盘事件删除输入框文字
function sliceHandler() {
  let newStr = paramFieldList[sltGroup.editFormItemIndex].correTable.slice(0, -1);
  paramFieldList[sltGroup.editFormItemIndex].correTable = newStr;
}
// 获取设计模式 选择字典
function getTableColumns() {
  correColumnList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictTable/getTableColumns';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { tableName: paramFieldList[sltGroup.editFormItemIndex].correTable } })
    .then((res: any) => {
      correColumnList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取获取设计模式选择字典失败',VxeNotifyType.error)
    });
}
function getTableDataList(row: any) {
  const columNameList = [];
  columNameList.push(row.correLabel);
  columNameList.push(row.correValue);

  tableDataList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictTableField/getTableFieldAndDataList';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { tableName: row.correTable, columNameList: columNameList.join(',') } })
    .then((res: any) => {
      tableDataList.push(...res.data);
    })
    .catch((err: any) => {
      // VxeMessage('获取可选的字典失败',VxeNotifyType.error)
    });
}
</script>

<style lang="scss" scoped>
#sysParamIdv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    :deep(.el-tabs) {
      height: 100%;
      .el-tabs__content {
        height: calc(100% - 39px);
        padding: 0;
        .el-tab-pane {
          height: 100%;
        }
      }
    }
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .right-Btn {
        margin: 0 0 0 5px;
        width: 40px;
      }
      // 右侧保存按钮
      .saveBtn {
        float: right;
        margin: 5px 10px;
      }
      .tableBody {
        height: calc(100% - 40px - 32px);
      }
      // 中间
      .tableBox {
        width: 100%;
        height: calc(100% - 40px);
        .spanIcon {
          padding: 0.1em 0.5em !important;
        }
      }
      .el-tabs {
        height: 100%;
        :deep(.el-tabs__content) {
          height: calc(100% - 40px - 60px);
          .el-tab-pane {
            height: 100%;
          }
        }
      }
      // 最左侧字典分类的树
      .sampleType {
        .tools-tree {
          min-width: 168px;
          padding: 0 5px 5px 5px;
          font-size: $font-size;
          border: none;
          .cirBtn {
            display: none;
            width: 16px;
            height: 16px;
            padding: 0px;
            margin-left: 10px;
          }
          .el-tree-node__content:hover {
            .cirBtn {
              display: inline-block !important;
            }
          }
        }
      }
      // 各个组件与右侧删除按钮的间距
      .vxe-checkbox {
        margin: 5px;
      }
      .vxe-radio {
        margin: 5px;
      }
      .vxe-switch {
        margin: -3px;
      }
    }
  }
}
.formBox {
  height: calc(100% - 45px);
}
</style>
